<?php

namespace App\Admin\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpFoundation\Response;
use App\Admin\Admin;

class Authenticate
{
    // 白名单路由
    private static array $whiteRouteName = [
        'admin.api.index',
    ];

    // 白名单控制器action
    private static array $whiteRouteAction = [
        'App\Admin\Controllers\Auth\TokenController@store',
        'App\Admin\Controllers\Auth\OAuthController@providers',
        'App\Admin\Controllers\Auth\OAuthController@redirect',
        'App\Admin\Controllers\Auth\OAuthController@exchange',
    ];


    public function handle(Request $request, Closure $next): Response
    {
        /**
         * 白名单路径和白名单控制器action
         * 这里面的路径不需要token也可以访问
         */
        if( in_array(Route::currentRouteName(), static::$whiteRouteName) || in_array(Route::currentRouteAction(), static::$whiteRouteAction) ){
            return $next($request);
        }

        if( Auth::guard('admin')->guest() ){
            return response([
                'code' => 401,
                'message' => '未携带有效token或者token已过期',
                'currentRouteAction' => Route::currentRouteAction(),
                's' => in_array(Route::currentRouteAction(), static::$whiteRouteAction),
            ], 401);
        }

        // 更新token活跃时间
        $this->updateLastActivity($request);

        return $next($request);
    }

    public function updateLastActivity($request)
    {
        if( $request->isMethod('GET') ){
           return false; 
        }

        $token = Admin::getAuthorization($request);
        DB::table('system_user_session')->where('id', $token)->update(['last_activity' => now()]);
    }
}
